<?php
namespace app\admin\controller\area;
use app\common\controller\Backend;
use think\Controller;
use think\Request;
use think\Session;
use think\facade\Lang;
use fast\Tree;
use fast\Cols;
use fast\Date;
use fast\Random;
use think\cache\Driver\File;
use Overtrue\Pinyin\ChinesePinyin;

class City extends Backend{
		protected $model = null;//模型对象
		protected $columnlist = array();
		public function initialize(){
				parent::initialize();
				$this->model = model('City');
				$this->columnarry = Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/module.php','',1);
		}
		
		public function index(){
				$columnlist = Cols::columnread('city');
				$flag = array();$options = array();$searchfileds = array();$searchdefault = array();
				foreach($columnlist as $v){
					$flag[] = $v['listorder'];
					if($v['options']){
						//把带有选项的列，提取出来。
						$options[$v['columnenname']] = $v['options'];
					}
					if($v['isshowsearch']){
						$searchfileds[$v['columnenname']] = $v['columntype'];
					}
				}
				array_multisort($flag, SORT_ASC, $columnlist);
				//设置过滤方法
				$this->request->filter(['strip_tags']);
				//如果发送的来源是Selectpage，则转发到Selectpage
				if ($this->request->request('pkey_name')){
					return $this->selectpage();
				}
				$searchfileds['pid'] = 'bigint';
				$searchdefault['pid'] = '0';
				list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds,null,$searchdefault);
				$limit = 200;
				$order = 'desc';
				$sort = 'listorder';
				$total = $this->model
				->where($where)
				->order($sort, $order)
				->count();
				$totalpage = 1;$page = 1;
				
				if($limit>0){
						$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
						//总页数
						if($offset>0){$page = intval($offset/$limit)+1;}
				}
				
				$list = $this->model
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
				for ($i = 0; $i < count($list); $i++) {
					if(isset($list[$i]['catid'])){
							$catarry = model('Category')->getCategoryByCache($list[$i]['catid']);
							$list[$i]['categoryname'] = $catarry['name'];
							$list[$i]['categorydiyname'] = $catarry['diyname'];
					}
					unset($list[$i]['intro']);unset($list[$i]['content']);
					$province = cache('province'.$list[$i]['pid']);
					if(isset($province['name'])){
						$list[$i]['provincename'] = $province['name'];
					}else{
						$province = model('Province')->findOrEmpty($list[$i]['pid']);	
						$list[$i]['provincename'] = $province['name'];
					}
					foreach ($options as $k => $v) {
							if(isset($list[$i][$k])){
									$arj = json_decode($v,true);
									$sarj = isset($arj[$list[$i][$k]])?$arj[$list[$i][$k]]:"";
									$list[$i][$k] = $sarj;
							}
					}
						
				}
				$result = array("total" => $total, "rows" => $list);
				$this->view->assign("lists",$result['rows']);
				$this->view->assign("listsjson",json_encode($result['rows']));
				$this->view->assign("columnlistjson",json_encode($columnlist));
				$this->view->assign("columnlist",$columnlist);
				$this->view->assign("total",$result['total']);
				$this->view->assign("offset",$offset);
				$this->view->assign("limit",$limit);
				$this->view->assign("totalpage",$totalpage);
				$this->view->assign("page",$page);
				//$this->view->assign("pid",$this->request->param('pid/d'));
				return $this->view->fetch('index');
		}
		public function select(){
				$columnlist = Cols::columnread('city');
				$flag = array();$options = array();$searchfileds = array();$searchdefault = array();
						foreach($columnlist as $v){
								$flag[] = $v['listorder'];
								if($v['options']){
										//把带有选项的列，提取出来。
										$options[$v['columnenname']] = $v['options'];
								}
								if($v['isshowsearch']){
										$searchfileds[$v['columnenname']] = $v['columntype'];
								}
						}
				array_multisort($flag, SORT_ASC, $columnlist);
				//设置过滤方法
				$this->request->filter(['strip_tags']);
				//如果发送的来源是Selectpage，则转发到Selectpage
				if ($this->request->request('pkey_name')){
						return $this->selectpage();
				}
				
				list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
				$order = 'desc';
				$sort = 'itemid';
				$total = $this->model
				->where($where)
				->order($sort, $order)
				->count();
				$totalpage = 1;$page = 1;
				if($limit>0){
						$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
						//总页数
						if($offset>0){$page = intval($offset/$limit)+1;}
				}
				$list = $this->model
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
				for ($i = 0; $i < count($list); $i++) {
						if(isset($list[$i]['catid'])){
								$catarry = model('Category')->getCategoryByCache($list[$i]['catid']);
								$list[$i]['categoryname'] = $catarry['name'];
								$list[$i]['categorydiyname'] = $catarry['diyname'];
						}
						unset($list[$i]['intro']);unset($list[$i]['content']);
						foreach ($options as $k => $v) {
								if(isset($list[$i][$k])){
										$arj = json_decode($v,true);
										$sarj = isset($arj[$list[$i][$k]])?$arj[$list[$i][$k]]:"";
										$list[$i][$k] = $sarj;
								}
						}
						$province = cache('province'.$list[$i]['pid']);
						if(isset($province['name'])){
								$list[$i]['provincename'] = $province['name'];
						}else{
								$list[$i]['provincename'] = '';
						}
						
				}
				$result = array("total" => $total, "rows" => $list);
				$this->view->assign("lists",$result['rows']);
				$this->view->assign("listsjson",json_encode($result['rows']));
				$this->view->assign("columnlistjson",json_encode($columnlist));
				$this->view->assign("columnlist",$columnlist);
				$this->view->assign("total",$result['total']);
				$this->view->assign("offset",$offset);
				$this->view->assign("limit",$limit);
				$this->view->assign("totalpage",$totalpage);
				$this->view->assign("page",$page);
				$this->view->assign("multiple",$this->request->get('multiple'));
				return $this->view->fetch();
		}
		public function add(){
			if ($this->request->isPost()){
					$Pinyin = new ChinesePinyin();
					$params = $this->request->param("row/a");
					if ($params){
							$fc = new File();
							$this->modelValidate = false;
							if ($this->dataLimit){
									$params[$this->dataLimitField] = $this->auth->id;
							}
							try{
									//是否采用模型验证
									if ($this->modelValidate){
											$name = basename(str_replace('\\', '/', get_class($this->model)));
											$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
											$this->model->validate($validate);
									}
									$params['py'] = strtoupper($Pinyin->TransformUcwordsOnlyChar($params['name']));
									$modelcity = \app\common\model\City::create($params);
									if ($modelcity !== false){
											$datacache = array();
											$datacache['name'] = $modelcity->name;
											$datacache['enname'] = $modelcity->enname;
											//$datacache['py'] = $modelcity->py;
											$datacache['acode'] = $modelcity->acode;
											$datacache['seed'] = $modelcity->seed;
											cache('city'.$modelcity->itemid,$datacache);
											$this->success();
									}else{
											$this->error($this->model->getError());
									}
							}
							catch (\think\exception\PDOException $e){
									$this->error($e->getMessage());
							}
					}
					$this->error(__('Parameter %s can not be empty', ''));
			}else{
				$pid = $this->request->param('pid');
				$this->view->assign("pid",$pid);
				/*
		        echo '带声调的汉语拼音';
		        echo $Pinyin->TransformWithTone("带声调的汉语拼音");
		        echo '<br/>';
		        echo '无声调的汉语拼音';
		        echo $Pinyin->TransformWithoutTone("无声调的汉语拼音");
		        echo '<br/>';
		        echo '首字母只包括汉字BuHanPinYin';   
		        echo $Pinyin->TransformUcwordsOnlyChar("首字母只包括汉字BuHanPinYin");
		        echo '<br/>';      
		        echo '首字母和其他字符如B区32号'; 
		        echo $Pinyin->TransformUcwords("首字母和其他字符如B区32号");
				*/
				$fc = new File();
				return $this->view->fetch();
			}
		}
		public function edit($ids = NULL){
			$row = $this->model->with([])->find($ids);
			if(isset($row['catid'])){
					$row['category'] = cache('category'.$row['catid']);
			}
			$fc = new File();
			if (!$row){$this->error(__('No Results were found'));}
			$adminIds = $this->getDataLimitAdminIds();
			if (is_array($adminIds)){
					if (!in_array($row[$this->dataLimitField], $adminIds)){
							$this->error(__('You have no permission'));
					}
			}
			if ($this->request->isPost()){
				$Pinyin = new ChinesePinyin();
				$params = $this->request->param("row/a");
				if ($params){
					try{
						//是否采用模型验证
						if ($this->modelValidate){
							$name = basename(str_replace('\\', '/', get_class($this->model)));
							$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
							$row->validate($validate);
						}
						$params['py'] = strtoupper($Pinyin->TransformUcwordsOnlyChar($params['name']));
						$result = $row->allowField(true)->save($params,['itemid' => $ids]);
						if ($result !== false){
							$datacache = array();
							$datacache['name'] = $params['name'];
							$datacache['enname'] = $params['enname'];
							$datacache['py'] = $params['py'];
							$datacache['acode'] = $params['acode'];
							$datacache['seed'] = $params['seed'];
							cache('city'.$ids,$datacache);
							$this->success();
						}else{
							$this->error($row->getError());
						}
					}catch (\think\exception\PDOException $e){
						$this->error($e->getMessage());
					}
				}
				$this->error(__('Parameter %s can not be empty', ''));
			}
			$this->view->assign("row", $row);
			return $this->view->fetch();
		}
		/**
		* 删除
		*/
		public function del($ids = ""){
			if($ids){
				$model = $this->model->get($ids);
				$model->delete();
			}
			$this->error(__('Parameter %s can not be empty', 'ids'));
		}
		/**
		* 删除类别
		* @internal
		*/
		public function dels(){
				if ($this->request->isPost()){
						$ids = $this->request->post("ids");
						$idarry = explode(',', $ids);
						foreach ($idarry as $k => $v) {
								if($v){
										$model = $this->model->get($v);
										$model->delete();
								}
						}
						$this->success();
						exit;
				}
				$this->error(__('Parameter %s can not be empty', 'ids'));
		}
		public function showlist(){
				$ids = $this->request->post('ids');
				$ischeck = $this->request->post('ischeck');
				model('Column')->where('itemid',$ids)->update(['isshowlist'=>($ischeck==='true'?1:0)]);
				$ll = model('Column')->getColumnsByModel('city');
				$lls = array();
				foreach ($ll as $k => $v) {
						$lls[ucfirst($v['columnenname'])] = $v;
				}
				$string = "<?php return ".var_export($lls, true)."; ?>";
				$filename = COLUMN_PATH.DS.'city.php';
				$result = file_put_contents($filename, $string);
				if(@$fp = fopen($filename,'wb')) {
						flock($fp, LOCK_EX);
						$len = fwrite($fp, $string);
						flock($fp, LOCK_UN);
						fclose($fp);
						echo $len;exit;
				} else {
						echo '失败了';exit;
				}
		}
		/**
		* 数据列表返回json数据
		*/
		public function ajaxlist(){
				$ll = array();$llary = array();$arrwhere = array();$returnarry = array();
				if($this->request->post('pid')){
						$arrwhere['pid'] = $this->request->post('pid');
				}
				if($this->request->get('tree')){
						$llv = collection(model('city')->where($arrwhere)->order('createtime', 'desc')->select())->toArray();
						Tree::instance()->init($llv);
						$ll = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
				}else{
						$ll = collection(model('city')->where($arrwhere)->order('createtime','desc')->select())->toArray();
				}
				print_r(json_encode($ll));exit;
		}
}
?>
